<template>
	<view class="home-content">
		<fun-scroll-view :topTabBars="topTabBars" :contentViewList='contentViewList' 
		@changeCurrent="changeCurrent"
		@likeFun="likeFun"
		@onRefresh="onRefresh"
		@scrolltolower="scrolltolower"
		@forwardFun="forwardFun"
		@clickAttention="clickAttention"
		ref="funScroll"/>
		<!-- 弹出提示框 -->
		<uni-popup ref="popup" type="center" animation @change="popuChange">
			<view class="popup-content">
				<view class="popup-title">转发</view>
				<view class="popu-prompt">确定转发此条趣事？</view>
				<view class="popu-butons">
					<view class="cancel-btn" @click="cancelPopu">取消</view>
					<view class="confirm-btn" @click="confirmPopu">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import funScrollView from '@/components/funScrollView/funScrollView.vue';
	import {Friend} from '@/model/friend.js';
	// 模拟请求数据
	import Datas from '@/datas/getDatas.js';
	import {User} from '@/model/user.js';
	import {Http} from '@/utils/http.js';
	import {utils} from '@/utils/utils.js';
	import {TheFun} from '@/model/theFun.js';
	import uniPopupMessage from '@/components/uni-popup/uni-popup-message.vue';
	import uniPopupDialog from '@/components/uni-popup/uni-popup-dialog.vue';
	import uniPopupShare from '@/components/uni-popup/uni-popup-share.vue';
	import {SocketChat} from '@/model/socketChat.js';
	import {Message} from '@/model/message.js';
	export default {
		data() {
			return {
				topTabBars:[],
				contentViewList:[],
				likeClick:false,
				funShares:[],
				funId:0,
				socketChat:'',
				chatList:[],
				comment:{
					commentLevel: 1,
					parentId: 0,
					funId: 0,
					toUid: '',
					toNickname: '',
					commentContent: '',
				},
				innerAudioContext:null,
				user:{},
				addFriendSockt:{}
			}
		},
		components:{
			uniPopupMessage,
			uniPopupDialog,
			uniPopupShare,
			funScrollView,
		},
		created() {
			
		},
		async onLoad() {
			this.$store.friendsMsgFlag = {}
			this.innerAudioContext = uni.createInnerAudioContext()
			this.innerAudioContext.src = "../../static/audio/pling.mp3"
			this.$store.innerAudioContext = this.innerAudioContext
			this.$store.loginStatus = true
			this.$store.user = this.$utils.getStorage("user")
			this.user = this.$store.user
			// 创建及时聊天长链接
			this.socketChat = new SocketChat(this.user.uid,this)
			this.socketChat.initSocketTask(this)
			this.$store.socketTask = this.socketChat
			// 创建添加好友长链接
			// this.addFriendSockt = new SocketAddFriend(this.user.uid,this)
			// this.addFriendSockt.initSocketTask(this)
			// this.$store.addFriendSockt = this.addFriendSockt
			uni.showLoading({
				mask:true,
				title:"加载中..."
			})
			this.contentViewList = await this.getFunShare()
			uni.hideLoading()
			uni.startPullDownRefresh();
			this.funShares.push(new TheFun(1,this.contentViewList[0].id,true))
			// this.toggle()
			if(!this.$utils.getStorage("chatList")){
				this.$utils.setStorage("chatList",[])
			}
			this.chatList = this.$utils.getStorage("chatList")
			this.$store.chatList = this.chatList
			let res = await Message.getUnreadMessage()
			if(res.code == 200){
				// "toFriendId": "9462328",
				// "nickName": "浮沉逆旅",
				// "avatarUrl": "http://qzapp.qlogo.cn/qzapp/1104455702/0AD12479F3E631951D20F0782DDA7ABE/30",
				// "uid": "8888888",
				// "messageList": [{
				// this.chatList.findIndex(item,index => {
				// 	res.data.forEach(msg => {
				// 		if(item.uid == )
				// 	})
				// })
				// 循环获取到的未读消息
				res.data.forEach(msg => {
					// 循环本地缓存的消息
					console.log(msg)
					this.chatList.forEach((item,index) => {
						// 判断本地缓存中是否存在该好友消息列表
						if(msg.uid == item.uid){
							// 存在好友消息列表，取出与未读消息长度的本地缓存的该好友消息最后几条
							// let tempArr = item.messageList.slice(item.messageList.length - msg.messageList.length, item.messageList.length)
							// 循环获取到的好友消息数组
							msg.messageList.forEach(msgItem=>{
								// 判断该好友未读消息是否已经被缓存
								// let msgItemIndex = tempArr.findIndex(e=>e.id == msgItem.id)
								let msgItemIndex = item.messageList.findIndex(e=>e.id == msgItem.id)
								// 如果没有被缓存则将未读消息添加到本地 消息缓存中
								if(msgItemIndex == -1){
									item.messageList.push(msgItem)
								}
							})
							console.log(this.chatList)
							// item.messageList.push(...msg.messageList)
							// 将有新消息的好友移动到数组头部
							let newList = this.chatList.splice(index,1)
							this.chatList.unshift(...newList)
						}
						item.tip = 0
						item.messageList.forEach(chatMsg=>{
							if(chatMsg.messageStatus == 2){
								item.tip += 1
							}
						})
					})
					// 判断本地缓存消息中是否存在好友
					let msgIndex = this.chatList.findIndex(item=>item.uid == msg.uid)
					if(msgIndex == -1){
						// 如果不存在则将好友以及消息添加到消息列表头部
						msg.tip = msg.messageList.length
						this.chatList.unshift(msg)
					}
					console.log(msgIndex)
				})
				if(res.data.length > 0){
					this.innerAudioContext.play()
					uni.showTabBarRedDot({
						index:2
					})
				}
			}
			// 将消息存入store中
			this.$store.chatList = this.chatList
			// 将消息存入本地缓存中
			this.$utils.setStorage("chatList",this.chatList)
			let addFes = await Friend.getFriendList({friendStatus:2})
			if(addFes != 200){
				return
			}
			addFes.data.forEach(item => {
				let chatIndex = this.$store.chatList.findIndex(chat=>chat.uid == "-1")
				if(chatIndex != -1){
					this.$store.chatList[chatIndex].messageList.forEach(addMsg=>{
						let addIndex = addMsg.findIndex(msg=>msg.uid == item.toFriendId)
						if(addIndex == -1){
							let obj = {
								avatar:("https://campus-fun.oss-cn-beijing.aliyuncs.com/avatar/512x512.png"),
								friendName:("新朋友"),
								contentText:(item.nickName + "请求添加你为好友"),
								contentType:(-1),
								toFriendId:(this.$store.user.uid),
								messageStatus:(-1),
								sendTime:(item.createTime),
								uid:("-1"),
							}
						}
					})
				}
			})
			console.log(this.chatList)
		},
		onPullDownRefresh() {
			setTimeout(function () {
				uni.stopPullDownRefresh();
				// 这里放刷新数据的方法
			}, 1000);
		},
		onNavigationBarButtonTap(e){
			if(e.index == 0){
				// TODO 点击左侧按钮
				
				return
			}
			// 点击右侧按钮
			uni.navigateTo({
				url:"../published/published"
			})
		},
		onNavigationBarSearchInputClicked() {
			uni.navigateTo({
				url:'../searchFun/searchFun'
			})
		},
		onShow() {
			uni.$on("refresh",async e=>{
				let dataIndex = this.contentViewList[e.scrollIndex].funSharePageResult.data.findIndex(item=>item.id == e.dataId)
				let res = await TheFun.getFunDetail({funId:e.dataId})
				if(res.code != 200) return;
				this.contentViewList[e.scrollIndex].funSharePageResult.data[dataIndex].isClick = res.data.isClick
				this.contentViewList[e.scrollIndex].funSharePageResult.data[dataIndex].likeNum = res.data.likeNum
				this.contentViewList[e.scrollIndex].funSharePageResult.data[dataIndex].commentNum = res.data.commentNum
				this.contentViewList[e.scrollIndex].funSharePageResult.data[dataIndex].forwardNum = res.data.forwardNum
			})
		},
		onHide() {
			this.$store.contentViewList = this.contentViewList
		},
		methods: {
			async getFunShare(){
				let res = await TheFun.getFunShare()
				if(res.code != 200){
					uni.showToast({
						icon:'none',
					    title: res.message,
					    duration: 2000
					});
				}
				return res.data;
			},
			async changeCurrent(e){
				if(!this.contentViewList[e].funSharePageResult){
					this.funShares.push(new TheFun(1,this.contentViewList[e].id,true))
					uni.showLoading({
						title:"加载中"
					})
					let res = await TheFun.getFunList({page:1,funClassifyId:this.contentViewList[e].id})
					uni.hideLoading()
					if(res.code != 200){
						uni.showToast({
							icon:'none',
						    title: res.message,
						    duration: 2000
						});
						return
					}
					this.contentViewList[e].funSharePageResult = res.data
				}
			},
			async likeFun(e){
				if(this.likeClick)
					return
				this.likeClick = true
				if(e.data.isClick){
					let res = await TheFun.likeFun({
						id:e.data.id,
						clickType:2,
						funOrTopic:1
					})
					this.likeClick = false
					if(res.code == 200){
						this.contentViewList[e.index].funSharePageResult.data[e.dataIndex].isClick = false
						this.contentViewList[e.index].funSharePageResult.data[e.dataIndex].likeNum -= 1
						return
					}
					uni.showToast({
						icon:'none',
					    title: res.message,
					    duration: 2000
					});
					return
				}
				let res = await TheFun.likeFun({
					id:e.data.id,
					clickType:1,
					funOrTopic:1
				})
				this.likeClick = false
				if(res.code == 200){
					this.contentViewList[e.index].funSharePageResult.data[e.dataIndex].isClick = true
					this.contentViewList[e.index].funSharePageResult.data[e.dataIndex].likeNum += 1
					return
				}
				uni.showToast({
					icon:'none',
				    title: res.message,
				    duration: 2000
				});
			},
			async onRefresh(index){
				let funIndex = this.funShares.findIndex(item=>
					item.funClassifyId == this.contentViewList[index].id
				)
				let res = await TheFun.getFunList({funClassifyId:this.funShares[funIndex].funClassifyId})
				if(!res.code == 200){
					uni.showToast({
						icon:'none',
					    title: res.message,
					    duration: 2000
					});
					return
				}
				this.funShares[funIndex].page = 1;
				this.funShares[funIndex].canRefresh = true
				this.contentViewList[index].funSharePageResult = res.data
				this.$refs.funScroll.hideRefresh()
			},
			async scrolltolower(index){
				uni.showLoading({
					mask:true,
					title:"加载中..."
				})
				let funIndex = this.funShares.findIndex(item=>
					item.funClassifyId == this.contentViewList[index].id
				)
				if(!this.funShares[funIndex].canRefresh) return;
				this.funShares[funIndex].page += 1;
				let res = await TheFun.getFunList(this.funShares[funIndex])
				uni.hideLoading()
				if(res.code != 200){
					uni.showToast({
						icon:'none',
					    title: res.message,
					    duration: 2000
					});
					return
				}
				this.contentViewList[index].funSharePageResult.data.push(...res.data.data)
				if(res.data.pages == this.funShares[funIndex]){
					this.funShares[funIndex].canRefresh = false
					this.$refs.funScroll.doenTolower()
				}
				this.$refs.funScroll.tolowerNoData()
			},
			async forwardFun(id){
				this.$refs.popup.open()
				this.funId = id
			},
			toggle() {
				this.$refs.popup.open()
			},
			hiddenpopup(e){
				this.$refs.popup.showPopup = false
			},
			cancelPopu(){
				this.hiddenpopup()
			},
			popuChange(e){
				console.log(e)
			},
			async confirmPopu(){
				this.hiddenpopup()
				uni.showLoading({
					mask:true,
					title:"加载中..."
				})
				let res = await TheFun.forwardFun({funId:this.funId})
				
				// console.log(res)
				if(res.code != 200){
					uni.showToast({
						icon:'none',
					    title: res.message,
					    duration: 2000
					});
					return 
				}
				uni.showToast({
					icon:'none',
				    title: "转发成功",
				    duration: 2000
				});
			},
			async clickAttention(uid){
				uni.showLoading({
					mask:true,
					title:"加载中..."
				})
				let res = await User.attentionUser({uid:uid})
				uni.hideLoading()
				if(res.code != 200 ){
					uni.showToast({
						icon:'none',
					    title: res.message,
					    duration: 2000
					});
					return 
				}
				uni.showToast({
					icon:'none',
				    title: "关注成功",
				    duration: 2000
				});
				this.contentViewList.forEach(item=>{
					if(item.funSharePageResult){
						item.funSharePageResult.data.forEach(graphic=>{
							if(graphic.uid == uid){
								graphic.isAttention = true
							}
						})
					}
				})
				console.log(this.contentViewList)
			},
			// clickInput(e){
			// 	this.comment.commentLevel = 1
			// 	this.comment.parentId = 0
			// 	this.comment.toUid = ''
			// 	this.comment.toNickname = ''
			// 	this.comment.commentContent = ''
			// 	this.comment.funId = e.id
			// 	this.showInput = true
			// 	console.log(e)
			// },
			// clickSend(e){
			// 	this.comment.commentContent = e
			// 	this.addcomment(this.comment)
			// },
			// async addcomment(param){
			// 	uni.showLoading({
			// 		mask:true,
			// 		title:"加载中..."
			// 	})
			// 	let res = await Comment.addComment(param)
			// 	uni.hideLoading()
			// 	if(res.code != 200){
			// 		uni.showToast({
			// 			icon:'none',
			// 		    title: res.message,
			// 		    duration: 2000
			// 		});
			// 		return
			// 	}
			// 	uni.showToast({
			// 		icon:'none',
			// 	    title: "评论成功",
			// 	    duration: 2000
			// 	});
			// 	if(param.commentLevel == 1){
			// 		this.commentList.unshift(res.data)
			// 		return
			// 	}
			// 	this.commentList[this.commentsIndex].childList.unshift(res.data)
			// },
		}
	}
</script>

<style>
	page{
		background-color: #f2f2f2;
	}
</style>
<style lang="scss" scoped>
	.popup-content{
		background-color: #FFF;
		width: 500rpx;
		box-sizing: border-box;
		border-radius: 20rpx;
		.popup-title{
			text-align: center;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 30rpx;
			color: $fun-theme-color;
			border-bottom: 1rpx #F2F2F2 solid;
		}
		.popu-prompt{
			font-size: 30rpx;
			color: #666666;
			padding: 20rpx 40rpx;
		}
		.popu-butons{
			display: flex;
			justify-content: space-between;
			align-items: center;
			.confirm-btn{
				background-color: $fun-theme-color;
				flex: 1;
				text-align: center;
				height: 80rpx;
				line-height: 80rpx;
				border-bottom-right-radius: 20rpx;
			}
			.cancel-btn{
				flex: 1;
				text-align: center;
				height: 80rpx;
				line-height: 80rpx;
				border-bottom-left-radius: 20rpx;
			}
		}
	}
</style>
